//2019/05/10 冷佳-区号组件
//使用说明
//<link href="../Css/ManageCss/Back_ManageList.css" rel="stylesheet" />
//js必须在vue.js后引入
//<script src="../Scripts/components.js"></script>
//必须挂在Vm实例内
//<phone :num="1"></phone>,num为必传参数，最好为连续数字
//传给后台的参数
//$('.subphone{num}').val();

//在模态框中使用
//<div class="znone"><phone :num="1"></phone><phone :num="2"></div>
//<div class="modal fade" id="PhoneModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabe" aria-hidden="true">
//<phone :num="1"></phone>
//<button type="button" data-dismiss="modal" class="btn btn-danger center-block">关闭</button>
//</div>
//<button type="button" data-toggle="modal" data-target="#PhoneModal" class="btn btn-primary">触发PhoneModal框</button>

var thisnum;
var phones = {
    template:
        `
        <div style='display:inline-block;'>
        <div class ="modal fade pt10 bg03 z1052" id="modelphone" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
        <div class ="modal-dialog modal-sm">
            <div class ="modal-content">
                <div class ="modal-header phoneheader">
                    <button type="button" class ="close closemodelphone" aria-hidden="true">
                        ×
                    </button>
                    <h4 class ="modal-title" id="myModalLabel">查找国家电话区号</h4>
                </div>
                <div class ="modal-body">
                    <div class ="searchCity">
                        <input type="text" :class ='"form-control ModelSearch"+num' style="width: 100%;" placeholder="请输入国家名称" />
                        <div class ="mserchcss modelserch1">

                        </div>
                    </div>
                    <div class ="bodyhide">
                        <input id="manualSearch" class ="manualSearch" oninput="if(value.length>4)value=value.slice(0,4)" style="width: 100%;" placeholder="请输入国家区号" type="number" />
                        <p class ="text-center" style="margin-top: 20px;">
                            <button type="button" id="btnConfirmback" class ="btn" onclick="countrycode();">返回</button>
                            <button type="button" id="btnConfirm" class ="btn btn-primary">确认</button>
                        </p>
                    </div>
                </div>
            </div>
        </div>
        </div>
            <div class='showphone' style='width:100%;'>
                <img :class ='"pimg pimg"+num' data-toggle="modal" data-target="#modelphone"/>
                <input type="tel" :class ='"form-control DeptPhoneCode DeptPhoneCode"+num'/>
                <input type="tel" :class ='"form-control DeptPhoneCodeNext DeptPhoneCodeNext"+num'/>
                <input type="hidden" :class ='"subphone"+num'/>
            </div>
        </div>
        `,

    props: ['num'],
    data() {
        return {
            thisnum: '',
        }
    },
    mounted() {
        $(document).on('click', '.closemodelphone', () => {
            $('#modelphone').modal('hide');
        });

        var self = this;
        $('.pimg' + this.num).attr({ 'src': '/Images/Flags/' + parent._country.IsoCode.toLowerCase() + '.png', 'title': parent._country.PhoneCode });
        $(document).on('click', '.pimg' + this.num, () => {
            if ($('.mserchp').text() == '暂无此城市') {
                $('.mserchp').text('');
            };
            //alert(this.num);
            thisnum = this.num;
            //$('.modelserch1').empty();
            //$('.pimg' + this.num).attr({ 'src': '/Images/Flags/' + parent._country.IsoCode.toLowerCase() + '.png', 'title': parent._country.PhoneCode });
        });
        var serachtimers;
        $('.ModelSearch' + this.num).bind('input propertychange', function () {
            clearTimeout(serachtimers);
            serachtimers = setTimeout(() => {
                //区号搜索
                if (this.value != '' || this.value != undefined) {
                    var data = { text: this.value, pageNumber: '20' };
                    ajaxRequest("post", "/api/Place/GetCountryIsoCode", data, function (data) {
                        $('.modelserch1').empty();
                        $.each(data, function (e, e1) {
                            //console.log(e1)
                            $('.modelserch1').append(
                                `
                        <p class='mserchp'><img src="/Images/Flags/${e1.CountryIsoCode.toLowerCase()}.png" title="${e1.PhoneCode}"/>${e1.CountryName}</p>
                    `
                            )
                        });
                        if (data == '') {
                            $('.modelserch1').empty();
                            $('.modelserch1').append(
                            `
                        <p class ='mserchp'>暂无此城市</p>
                    `
                            )
                        }
                    });
                }
            },1500);
        })
        //最终传的参数
        $(document).on('input', '.DeptPhoneCode' + this.num + ',' + '.DeptPhoneCodeNext' + this.num, () => {
            $('.subphone' + this.num).val('+' + $('.pimg' + this.num).attr('title') + ' (' + $('.DeptPhoneCode' + this.num).val() + ') ' + FormatPhone($('.DeptPhoneCodeNext' + this.num).val()));
            //console.log($('.subphone' + this.num).val())
        });
        //同一组件多次使用赋值
        $(document).on('input', '.DeptPhoneCode' + this.num, function () {
            $('.DeptPhoneCode' + self.num).val($(this).val());
            //console.log($('.DeptPhoneCode' +self.num).val());
        });
        $(document).on('input', '.DeptPhoneCodeNext' + this.num, function () {
            $('.DeptPhoneCodeNext' + self.num).val($(this).val());
            //console.log($('.DeptPhoneCodeNext' + self.num).val());
        });

        //更改选择区号img
        $(document).on('click', '.modelserch1>p', function () {
            $('.pimg' + thisnum).attr({ 'src': $(this).children().attr('src'), 'title': $(this).children().attr('title') });
            //防止区号变动，最终参数未变动
            $('.subphone' + thisnum).val('+' + $('.pimg' + thisnum).attr('title') + ' (' + $('.DeptPhoneCode' + thisnum).val() + ') ' + FormatPhone($('.DeptPhoneCodeNext' + thisnum).val()));
            $('#modelphone').modal('hide');
        });
    },
};


//2019/05/13 冷佳-地区组件
//使用说明:<region :num="1"></region>,num值与phone组件同理
//传给后台的参数
//$('.subregion{num的值}').val()

//7月4号改进
//1:用户输入完2秒后执行
//2:空值提示去除

var adr = {
    template:
        `
        <div style='display:inline-block;position: relative;'>
        <input type="text" :class ='"form-control RegionseSec"+num' errmsg="发证国家ID不为空"/>
        <input type="hidden" :class ='"subregion"+num'>
        <ul :class ='"RegionseData RegionseData"+num'>
        </ul>
        </div>
        `,
    props: ['num'],
    mounted() {
        var serachtimer;
        var self = this;
        $('.RegionseSec' + this.num).bind('input propertychange', function () {
            clearTimeout(serachtimer);
            serachtimer = setTimeout(() => {
                if (this.value == '') {
                    $('.RegionseData' + self.num).empty();
                    $('.RegionseData' + self.num).hide();
                    return
                } else {
                    $('.RegionseData' + self.num).show();
                    $('.RegionseData' + self.num).empty();
                    var data = { text: this.value, pageNumber: '20', count: '20' };
                    ajaxRequest("post", "/api/Place/GetCities", data, function (data) {
                        $.each(data, function (e, e1) {
                            $('.RegionseData' + self.num).append(
                            `
                                <li data-key="${e1.PlaceId}" data-name="${e1.FormattedName}">${e1.PlaceName}</li>
                            `
                            )
                        });
                        if (data == '') {
                            $('.RegionseData' + self.num).append(
                            `
                                <li>暂无此城市</li>
                            `
                            )
                        };

                    });

                }
            }, 1500)

            //console.log(self.num+'--'+this.value);
        });

        //搜索内容
        $(document).on('click', '.RegionseData' + self.num + '>li', function () {
            $('.RegionseSec' + self.num).val($(this).data('name'));
            $('.subregion' + self.num).val($(this).data('key'));
            $('.RegionseData' + self.num).hide();
        });
        //文本框
        $(document).on('click', '.RegionseSec' + this.num, function () {
            $(this).val('');
            $('.subregion' + self.num).val('');
            $('.RegionseData' + self.num).empty();
            $('.RegionseData' + self.num).hide();
        });

        $('.RegionseSec' + this.num).blur(function () {
            setTimeout(() => { $('.RegionseData' + self.num).hide()},200)
        })
    }
}


//2019/05/13 冷佳-语言组件
//num必传,choice=false：无默认语言,不传则有默认语言

//若存在语言,添加.langistrue
//本地化语言是否重复,在data中声明个localdata:[],存放接口存在的语言,1为num传的值;
//$('.lang1').click(() => {
//    this.localdata.forEach((e) => {
//        setTimeout(() => {
//            $(`.` + e + `1`).addClass('langistrue');
//        }, 100)
//    })
//})

//lang使用方法
//components: {
//        'language': lang
//    },

//<language :num="1" ></language>
//传后台的值：$('.sublang{num的值}').text();

//模态框
//<div class="znone"><language :num="2"></language></div>
//<span data-toggle="modal" data-target="#ModalLang" class ='lang lang2'></span>


var langid = 1;
var lang = {
    template:
        `
        <div style='display:inline-block;'>

<div class ="modal fade zmax" id="ModalLang" tabindex="-1" role="dialog" aria-hidden="true">
    <div class ="modal-dialog langdialog">
        <div class ="modal-content">
            <div class ="modal-header langheader">
                <button type="button" class ="close" data-dismiss="modal" aria-hidden="true">&times; </button>
                <h4 class ="modal-title">语言（language）</h4>
            </div>
            <div class ="modal-body">
                <div :class ='"langdata langdata"+num'>

                </div>
            </div>
            <div class ="modal-footer">
                <button type="button" class ="btn btn-danger" data-dismiss="modal">关闭</button>
            </div>
        </div>
    </div>
</div>

        <span data-toggle="modal" data-target="#ModalLang" :class ='"lang lang"+num'>选择语言</span>
        <span :class ='"dnone sublang"+num'></span>
        </div>
        `,
    props: ['num', 'choice'],
    mounted() {
        var self = this;
        //默认无语言
        if (this.choice == false) {
            $('.lang' + self.num).text('请选择');
            $('.sublang' + self.num).text('');
        } else {
            //浏览器默认语言
            $.each(parent._languages, function (e, e1) {
                if (e == (navigator.language || navigator.userLanguage).toLocaleLowerCase()) {
                    $('.lang' + self.num).text(e1);
                    $('.sublang' + self.num).text(e);
                }
            });
        }


        //点击标识
        $(document).on('click', '.lang' + this.num, function () {
            langid = self.num;
            $(".langdata").empty();
            $.each(parent._languages, function (e, e1) {
                //全部语言
                $(".langdata").append(
                    `
        <span data-key=${e} class =${e}` + langid + ` >${e1}</span>
        `
                )
            });
        });
        //语言点击
        $(document).on('click', '.langdata>span', function () {
            $('.lang' + langid).text($(this).text());
            $('.sublang' + langid).text($(this).data('key'));
            $('#ModalLang').modal('hide');
        });
    }
}

//在哪用到就在哪个实例中注册组件
//components:{}
//组件实例
//var vms = new Vue({
//    el: '.coms',
//    data() {
//        return {
//            num: '',
//        }
//    },
//    components: {
//        //电话,传真
//        'phone': phones,
//        //国家,地区
//        'region': adr,
//        //语言
//        'language': lang
//    },
//})

//公用方法

//语言key转value
Vue.filter('langname', function (key) {
    var langn = '';
    $.each(parent._languages, function (e, e1) {
        if (key == e) {
            langn = e1
        }
    })
    return langn
});

function langname(key) {
    var langn = '';
    $.each(parent._languages, function (e, e1) {
        if (key == e) {
            langn = e1
        }
    })
    return langn
};

//注：组件num，传值最小为1，且为连续数字
//清空phone组件内容,有几个传几，适用于创建
function clearphone(num) {
    for (var i = 1; i <= num; i++) {
        $('.DeptPhoneCode' + i).val('');
        $('.DeptPhoneCodeNext' + i).val('');
        $('.subphone' + i).val('');
    };
}
//组件赋值展示，适用于修改
//updatephone(有几个phone组件,:num为有序数字,要修改的文字标签的class值)
//$('.DeptPhoneCodeNext1').val(phoner($('.sphone1').text().replace(/-/g, '')));
function updatephone(num, class1) {
    for (var i = 1; i <= num; i++) {
        $('.DeptPhoneCode' + i).val(phonec($('.' + class1 + i).text()));
        $('.DeptPhoneCodeNext' + i).val(phoner($('.' + class1 + i).text().replace(/-/g, '')));
        $('.subphone' + i).val($('.' + class1 + i).text());
    };
}
//括号中
function phonec(str) {
    return str.substring(str.indexOf("(") + 1, str.indexOf(")"));
}
//括号右
function phoner(str) {
    return str.substring(str.indexOf(')') + 1);
}
//格式化输入的号码,传入：+86(22)18866668888
function FormatPhone(str) {
    var newstr = str.indexOf(')') + 1;
    str = str.substring(newstr);
    if (str.length >= 4 && str.length < 8) {
        return str.substring(0, 3).concat('-') + str.substring(3);
    } else if (str.length >= 8) {
        return str.substring(0, 3).concat('-') + str.substring(3, 7).concat('-') + str.substring(7)
    } else {
        return str
    }
};
//格式化输入的号码,传入：+86(22)18866668888
Vue.filter('FormatPhone', function (str) {
    var newstr = str.indexOf(')') + 1;
    str = str.substring(newstr);
    if (str.length >= 4 && str.length < 8) {
        return str.substring(0, 3).concat('-') + str.substring(3);
    } else if (str.length >= 8) {
        return str.substring(0, 3).concat('-') + str.substring(3, 7).concat('-') + str.substring(7)
    } else {
        return str
    }
})
//转blob:base64转blob再上传
function blob(dataURI) {
    var dataUrlArray = dataURI.split(',');
    var fileType = dataUrlArray[0].split(':')[1].split(';')[0];
    var binary = atob(dataUrlArray[1]);
    var len = binary.length;
    var byteArray = new Uint8Array(len);
    for (var i = 0; i < len; i++) {
        byteArray[i] = binary.charCodeAt(i);
    }
    return new Blob([byteArray], { type: fileType });
}
//格林威治时间转换
Vue.filter('Gtimes', function (utcDateString) {
    if (!utcDateString) {
        return "";
    }
    function pad(n) { return n < 10 ? '0' + n : n; }
    if (!/GMT/.test(utcDateString) && !/Z/.test(utcDateString)) {
        utcDateString += "Z";
    }
    var d = new Date(utcDateString);
    if (isNaN(d.valueOf())) return "";

    return d.getFullYear() + "-" + pad(d.getMonth() + 1) + "-" + pad(d.getDate()) + " " + pad(d.getHours()) + ":" + pad(d.getMinutes());
});
//格式化日期
function Times(time) {
    var date = new Date(time);
    var year = date.getFullYear();
    var month = date.getMonth() + 1;
    var day = date.getDate();
    var hour = date.getHours();
    var minutes = date.getMinutes();
    var seconds = date.getSeconds();
    var finish = year + '-' + (month < 10 ? "0" + month : month) + '-' + (day < 10 ? "0" + day : day);
    return finish;
}
//一般格式时间精确到时分秒
Vue.filter('Dtimes', function (time) {
    var date = new Date(time);
    var year = date.getFullYear();
    var month = date.getMonth() + 1;
    var day = date.getDate();
    var hour = date.getHours();
    var minutes = date.getMinutes();
    var seconds = date.getSeconds();
    var finish = year + '-' + (month < 10 ? "0" + month : month) + '-' + (day < 10 ? "0" + day : day) + ' ' + (hour < 10 ? '0' + hour : hour) + ':' + (minutes < 10 ? '0' + minutes : minutes) + ':' + (seconds < 10 ? '0' + seconds : seconds);
    return finish;
});

/*图片*/
//.manphoto {
//    width:220px;
//    height:260px;
//    padding-bottom:20px;
//}
/*图片大小*/
//  #perPhoto {
//    cursor:pointer;
//    width:100%;
//    height:100%;
//}
//清空图片
//$('.getphone').attr('src', '../Images/defaultAvatar.jpg');
//$('.getphone').removeClass('width100');
//当前不存在图片
//if (!$('.getphone').hasClass('width100')) {
//    etips('请上传个人图片');
//    return
//}
//添加或修改图片
//<td colspan="2">
//    <p class="manphoto" data-toggle="modal" data-target="#avatar-modal" onclick="photoModal(this);">
//        <img class="finalImg getphone" src="../Images/defaultAvatar.jpg" />
//    </p>
//</td>
//展示图片
//<img class="finalImg getphone" src="../Images/defaultAvatar.jpg" />



//loading
//<div id="mloading" class="modal fade">
//    <div id="loading" class="loading">加载中...</div>
//</div>
//mounted() {
//    $('#mloading').modal({backdrop: 'static', keyboard: false},'show');
//}
//ajax请求渲染完毕
//$('#mloading').modal('hide');



//错误消息提示
//  <div class="alert alert-danger errortips dnone">
//    <strong class="etipsmsg"></strong>
//  </div>
//正确消息提示
//  <div class="alert alert-success successtips dnone">
//    <strong class="stipsmsg"></strong>
//  </div>
//错误提示动画
function etips(msg) {
    $('.etipsmsg').text(msg)
    $('.errortips').fadeIn('fast');
    setTimeout(function () {
        $('.errortips').fadeOut('fast')
    }, 2000)
}
//正确提示动画
function stips(msg) {
    $('.stipsmsg').text(msg)
    $('.successtips').fadeIn('fast');
    setTimeout(function () {
        $('.successtips').fadeOut('fast')
    }, 2000)
}

//发送倒计时showtime(30)
//<input type="button" class="form-control sendemail" value="发送验证码" @click="subemail()"/>
function showtime(t) {
    $(".sendemail").attr('disabled', true);
    for (i = 1; i <= t; i++) {
        setTimeout("update_p(" + i + "," + t + ")", i * 1000);
    }
}
function update_p(num, t) {
    if (num == t) {
        $('.sendemail').val('重新发送');
        $(".sendemail").attr('disabled', false);
    }
    else {
        printnr = t - num;
        $('.sendemail').val(printnr + '秒后重新发送');
    }
}

//拉伸
jQuery(function ($) {
    var doc = $(document),
        dl = $("div.left"),
        dc = $("div.center");
    var sum = dl.width() + dc.width() +
        $("div.handler").mousedown(function (e) {
            var me = $(this);
            var deltaX = e.clientX -
                (parseFloat(me.css("left")) || parseFloat(me.prop("clientLeft")));
            doc.mousemove(function (e) {
                var lt = e.clientX - deltaX;
                lt = lt < 0 ? 0 : lt;
                lt = lt < 270 ? 270 : lt;
                lt = lt > sum - me.width() ? sum - me.width() : lt;
                lt = lt > $(document).width() - 25 ? $(document).width() - 25 : lt;
                me.css("left", lt + "px");
                dl.width(lt);
                dc.width(sum - lt - me.width());
            });
        }).width();

    doc.mouseup(function () {
        doc.unbind("mousemove");
    });
    doc[0].ondragstart = doc[0].onselectstart = function () {
        return false;
    };
})
//<div class="companylist left">
//    <h2>公司</h2>
//    <ul class="companylistli">
//        <li>111</li>
//    </ul>
//    <div class="handler"></div>
//</div>